﻿Imports System
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports Newtonsoft.Json
Imports System.Xml
Imports System.Xml.Xsl
Imports System.Reflection
Imports System.Text
Imports System.IO



Public Class Form1

    Private Sub ShowDataFile(iType As Integer)

        Dim sFilePath As String = AppDomain.CurrentDomain.BaseDirectory

        Select Case iType
            Case 0
                sFilePath += "TopicData.xml"

            Case 1
                sFilePath += "AllTopicsData.xml"

            Case 2
                sFilePath += "MyData.xml"

            Case 3
                sFilePath += "Verbatims.xml"

        End Select

        If Not File.Exists(sFilePath) Then
            MsgBox("Data file does not exist: " + sFilePath, MsgBoxStyle.Information, "Open Data File")
            Exit Sub
        End If

        Dim value As System.Diagnostics.ProcessStartInfo
        value = New System.Diagnostics.ProcessStartInfo("wordpad.exe", sFilePath)
        System.Diagnostics.Process.Start(value)

    End Sub

    Private Function GetDaysBack(iDays As Integer) As String

        Dim yesterDay As String = DateTime.Today.AddDays(-iDays).Day
        Dim thisMonth As String = DateTime.Today.AddDays(-iDays).Month
        Dim thisYear As String = DateTime.Today.AddDays(-iDays).Year

        Return thisYear + "-" + thisMonth + "-" + yesterDay + "T00:00:00.0"

    End Function

    Private Function GetTopicFilter(sContentId As String) As String

        Dim sParam As String = "{ " &
                                    """Services"": [""Active Directory""], " &
                                    """Locales"": [""en-us""], " &
                                    """VerbatimsText"": false, " &
                                    """IsLiveOnly"": true, " &
                                    """WithByVisitorMeasures"": false, " &
                                    """DirectReadFromKusto"": false, " &
                                    """StartDate"": ""2015-11-02T00:00:00.0"", " &
                                    """EndDate"": """ & GetDaysBack(1) & """, " &
                                    """granularLevel"": 0, " &
                                    """AbsoluteDateRange"": true, " &
                                    """Skip"": 0, " &
                                    """Take"": " & My.Settings.MaxRows.ToString

        sParam += ", ""ContentIds"": [""" & sContentId & """]"
        sParam += "}"

        Return sParam
    End Function

    Private Function GetAllTopicsFilter() As String

        Dim sParam As String = "{ " &
                                    """Services"": [""Active Directory""], " &
                                    """Locales"": [""en-us""], " &
                                    """VerbatimsText"": false, " &
                                    """IsLiveOnly"": true, " &
                                    """WithByVisitorMeasures"": false, " &
                                    """DirectReadFromKusto"": false, " &
                                    """StartDate"": """ & GetDaysBack(31) & """, " &
                                    """EndDate"": """ & GetDaysBack(1) & """, " &
                                    """granularLevel"": 0, " &
                                    """AbsoluteDateRange"": false, " &
                                    """Skip"": 0, " &
                                    """Take"": " & My.Settings.MaxRows.ToString

        If My.Settings.Author.Length > 1 Then
            sParam += ", ""Authors"": [""" & My.Settings.Author.Trim & """]"
        End If

        sParam += "}"

        Return sParam
    End Function

    Private Function GetVerbatimsFilter() As String

        Dim sParam As String = "{ " &
                                    """Services"": [""Active Directory""], " &
                                    """Locales"": [""en-us""], " &
                                    """VerbatimsText"": true, " &
                                    """IsLiveOnly"": true, " &
                                    """WithByVisitorMeasures"": false, " &
                                    """DirectReadFromKusto"": false, " &
                                    """StartDate"": ""2015-11-02T00:00:00.0"", " &
                                    """EndDate"": """ & GetDaysBack(1) & """, " &
                                    """granularLevel"": 0, " &
                                    """AbsoluteDateRange"": false, " &
                                    """Skip"": 0, " &
                                    """Take"": " & My.Settings.MaxRows.ToString

        If My.Settings.Author.Length > 1 Then
            sParam += ", ""Authors"": [""" & My.Settings.Author.Trim & """]"
        End If

        sParam += "}"

        Return sParam
    End Function
    Private Sub ShowLoadFilter()
        MsgBox(GetFilterStringUnmasked(GetAllTopicsFilter), Nothing, "Load Filter")
    End Sub

    Private Sub GetAllTopicsData()
        If My.Settings.Author.Length < 1 Then
            MsgBox("No author configured", MsgBoxStyle.Information, "Get Rollup Data")
            Exit Sub
        End If

        GetTopicRollup(GetAllTopicsFilter, 1)

        Me.Cursor = Cursors.WaitCursor
        Form2.ShowDialog()
    End Sub

    Private Sub GetComboData()

        comboTopicFilter.ComboBox.DataSource = Nothing
        comboTopicFilter.ComboBox.Items.Clear()

        comboDrilldown.ComboBox.DataSource = Nothing
        comboDrilldown.ComboBox.Items.Clear()

        comboVerbatims.ComboBox.DataSource = Nothing
        comboVerbatims.ComboBox.Items.Clear()

        If (My.Settings.TopicFilter.Length > 2) Then
            comboTopicFilter.ComboBox.DisplayMember = "Text"
            comboTopicFilter.ComboBox.ValueMember = "Value"

            comboDrilldown.ComboBox.DisplayMember = "Text"
            comboDrilldown.ComboBox.ValueMember = "Value"

            comboVerbatims.ComboBox.DisplayMember = "Text"
            comboVerbatims.ComboBox.ValueMember = "Value"


            Dim tblItems As New DataTable
            tblItems.Columns.Add("Text", GetType(String))
            tblItems.Columns.Add("Value", GetType(String))

            Dim sFilters As String = My.Settings.TopicFilter
            Dim sFilter As String

            tblItems.Rows.Add("", "")
            For Each sFilter In sFilters.Split("|")
                Dim arrItems As String() = sFilter.Split(";")
                tblItems.Rows.Add(arrItems(0), arrItems(1))
            Next
            comboTopicFilter.ComboBox.DataSource = tblItems
            comboDrilldown.ComboBox.DataSource = tblItems
            comboVerbatims.ComboBox.DataSource = tblItems
        End If
    End Sub

    Private Sub GetTitle()
        Dim sAuthor As String = My.Settings.Author.Trim
        Dim sRet As String = "Docs Toolbox"

        If sAuthor.Length > 1 Then
            sRet += " - " + sAuthor
        End If

        Me.Text = sRet
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        GetTitle()
        GetComboData()
        ToolStripStatusLabel1.Text = "Ready"
    End Sub

    Private Sub Form1_SizeChanged(sender As Object, e As EventArgs) Handles Me.SizeChanged
        TabControl1.Dock = DockStyle.None 'set dock to none to allow resize
        TabControl1.Size = New Size(New Point(3, 3)) ' set size anything you want
        TabControl1.Dock = DockStyle.Fill 'set dock to fill to fit to container
    End Sub

    Private Function CutFirstLast(iSource As String) As String
        If iSource.Length < 3 Then
            Return ""
        Else
            Return iSource.Substring(1, iSource.Length - 2)
        End If
    End Function

    Private Sub LoadIndex()
        Try
            If My.Settings.AllTopicsData.Length < 2 Then
                Exit Sub
            End If

            Dim xmlDoc As New XmlDocument
            xmlDoc.LoadXml(My.Settings.AllTopicsData)

            ToolStripStatusLabel1.Text = "Requesting data - please wait..."
            Dim settings As New XsltSettings
            settings.EnableScript = True

            Dim myAssembly As [Assembly]
            myAssembly = [Assembly].GetExecutingAssembly()
            Dim myReader As XmlTextReader = New XmlTextReader(myAssembly.GetManifestResourceStream("DocsToolbox.Index.xslt"), XmlNodeType.Document, Nothing)

            Dim xslt As New XslCompiledTransform
            xslt.Load(myReader, settings, New XmlUrlResolver())

            Dim argsList As New XsltArgumentList
            If Not IsNothing(comboDrilldown.ComboBox.SelectedValue) Then
                If (comboDrilldown.ComboBox.SelectedValue.ToString.Length > 2) Then
                    argsList.AddParam("topicfilter", "", comboDrilldown.ComboBox.SelectedValue.ToString.Trim)
                End If
            End If

            Dim output As New StringWriter
            xslt.Transform(xmlDoc.CreateNavigator, argsList, output)
            WebBrowser3.DocumentText = output.ToString

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Load Index")
        Finally
            Me.Cursor = Cursors.Default
            ToolStripStatusLabel1.Text = "Ready"
        End Try
    End Sub

    Private Sub ShowVerbatims()
        Try

            Dim sXml As String
            sXml = My.Settings.VerbatimsData

            If (sXml.Length < 2) Then
                Exit Sub
            End If


            Dim xmlDoc As New XmlDocument
            xmlDoc.LoadXml(sXml)

            Dim settings As New XsltSettings
            settings.EnableScript = True

            Dim myAssembly As [Assembly]
            myAssembly = [Assembly].GetExecutingAssembly()
            Dim myReader As XmlTextReader = New XmlTextReader(myAssembly.GetManifestResourceStream("DocsToolbox.Verbatims.xslt"), XmlNodeType.Document, Nothing)


            Dim xslt As New XslCompiledTransform
            xslt.Load(myReader, settings, New XmlUrlResolver())

            Dim argsList As New XsltArgumentList
            If Not IsNothing(comboVerbatims.ComboBox.SelectedValue) Then
                If (comboVerbatims.ComboBox.SelectedValue.ToString.Length > 2) Then
                    argsList.AddParam("topicfilter", "", comboVerbatims.ComboBox.SelectedValue.ToString.Trim)
                End If
            End If

            Dim output As New StringWriter
            xslt.Transform(xmlDoc.CreateNavigator, argsList, output)
            WebBrowser4.DocumentText = output.ToString

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Show Verbatims")
        End Try

    End Sub
    Private Async Function GetTopicRollup(sFilter As String, iType As Integer) As Task
        Try
            ToolStripStatusLabel1.Text = "Requesting data - please wait..."
            Dim sUri As String = "http://csiwebapi.cloudapp.net/Rollups/ByTopicRollup"

            Dim myClient As New HttpClient
            myClient.DefaultRequestHeaders.Accept.Clear()
            myClient.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))

            Dim stringContent As StringContent = New StringContent(sFilter, Encoding.UTF8, "application/json")
            Dim httpResponse As HttpResponseMessage = Await myClient.PostAsync(sUri, stringContent)

            If httpResponse.StatusCode <> System.Net.HttpStatusCode.OK And httpResponse.StatusCode <> System.Net.HttpStatusCode.BadRequest Then
                Throw New SystemException(httpResponse.StatusCode.ToString + vbCrLf + httpResponse.RequestMessage.ToString)
            End If

            Dim retJsonText As String = Await httpResponse.Content.ReadAsStringAsync()
            If httpResponse.StatusCode = System.Net.HttpStatusCode.BadRequest Then
                Throw New SystemException(httpResponse.StatusCode.ToString + vbCrLf + retJsonText)
            End If

            Dim retRaw As String = retJsonText
            retJsonText = retJsonText.Substring(11)
            retJsonText = retJsonText.Substring(0, retJsonText.LastIndexOf(","))

            Dim json As JsonSerializer = New JsonSerializer
            json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
            json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace
            json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
            json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore

            Dim xmlDoc As XmlDocument = JsonConvert.DeserializeXmlNode(retRaw, "Root")

            If xmlDoc.DocumentElement.SelectSingleNode("TotalCount").InnerText = "0" Then
                MsgBox(GetFilterStringUnmasked(sFilter), Nothing, "Request Returned No Data")
                Exit Function
            End If

            Dim sAppFolder As String = AppDomain.CurrentDomain.BaseDirectory


            Select Case iType
                Case 0
                    xmlDoc.Save(sAppFolder + "TopicData.xml")
                    ShowTopicSummary(xmlDoc)
                Case 1
                    xmlDoc.Save(sAppFolder + "AllTopicsData.xml")
                    ToolStripStatusLabel1.Text = "Processing data"
                    ProcessRollups(xmlDoc)
                Case 2
                    xmlDoc.Save(sAppFolder + "Verbatims.xml")
                    My.Settings.VerbatimsData = xmlDoc.OuterXml
                    ShowVerbatims()
            End Select

            ToolStripStatusLabel1.Text = "Ready"

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Load Rollup Data")
        Finally
            Me.Cursor = Cursors.Default
            Form2.Close()
        End Try
    End Function

    Private Function GetFilterStringUnmasked(iFilterString As String) As String
        Dim sFilter As String = iFilterString
        sFilter = sFilter.Replace("{", "")
        sFilter = sFilter.Replace("}", "")
        sFilter = sFilter.Replace("[", "")
        sFilter = sFilter.Replace("]", "")
        sFilter = sFilter.Replace("""", "")

        Dim sRes As String = ""
        Dim sTmp As String

        For Each sTmp In sFilter.Split(",")
            sRes += sTmp + vbCrLf
        Next

        Return sRes
    End Function

    Private Sub ProcessRollups(iXmlsourceDoc As XmlDocument)
        Try
            Dim xmlSource As XmlDocument = iXmlsourceDoc

            Dim xmlTarget As New XmlDocument
            xmlTarget.LoadXml("<?xml version=""1.0"" encoding=""utf-8"" ?><Root></Root>")

            Dim curNode As XmlNode
            For Each curNode In xmlSource.DocumentElement.SelectNodes("//Rollups")
                Dim topicKey As String = curNode.SelectSingleNode("TopicKey").InnerText

                Dim targetNode As XmlNode = xmlTarget.SelectSingleNode("//Rollups[TopicKey = '" + topicKey + "']")
                If IsNothing(targetNode) Then
                    Dim newRollupsNode As XmlNode = xmlTarget.CreateElement("Rollups")
                    Dim targetNewNode As XmlNode = xmlTarget.DocumentElement.AppendChild(newRollupsNode)

                    Dim newCountNode As XmlNode = xmlTarget.CreateElement("RecordCount")
                    newCountNode.InnerText = 1
                    targetNewNode.AppendChild(newCountNode)

                    Dim sNodes As String = "TopicKey|ContentId|Title|RatingCount|HelpfulCount|TotalPageViewCount|DistinctVisitorCount|LiveUrl"
                    Dim sNodeName As String
                    For Each sNodeName In sNodes.Split("|")
                        Dim dataNode As XmlNode = xmlTarget.CreateElement(sNodeName)
                        dataNode.InnerText = curNode.SelectSingleNode(sNodeName).InnerText
                        targetNewNode.AppendChild(dataNode)
                    Next

                    Dim topicNameNode As XmlNode = xmlTarget.CreateElement("TopicName")
                    Dim sTopicName As String = curNode.SelectSingleNode("LiveUrl").InnerText
                    sTopicName = sTopicName.Substring(sTopicName.LastIndexOf("/") + 1)
                    topicNameNode.InnerText = sTopicName
                    targetNewNode.AppendChild(topicNameNode)
                Else
                    targetNode.SelectSingleNode("RecordCount").InnerText = CInt(targetNode.SelectSingleNode("RecordCount").InnerText) + 1

                    Dim sNodes As String = "RatingCount|HelpfulCount|TotalPageViewCount|DistinctVisitorCount"
                    Dim sNodeName As String
                    For Each sNodeName In sNodes.Split("|")
                        Dim iVal1 As Integer = CInt(curNode.SelectSingleNode(sNodeName).InnerText)
                        Dim iVal2 As Integer = CInt(targetNode.SelectSingleNode(sNodeName).InnerText)
                        targetNode.SelectSingleNode(sNodeName).InnerText = iVal1 + iVal2
                    Next
                End If
            Next

            My.Settings.AllTopicsData = xmlTarget.OuterXml
            ShowTable(xmlTarget)

        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub ShowTable(xmlDoc As XmlDocument)
        Try
            Dim settings As New XsltSettings
            settings.EnableScript = True

            Dim myAssembly As [Assembly]
            myAssembly = [Assembly].GetExecutingAssembly()
            Dim myReader As XmlTextReader = New XmlTextReader(myAssembly.GetManifestResourceStream("DocsToolbox.Ratings.xslt"), XmlNodeType.Document, Nothing)


            Dim xslt As New XslCompiledTransform
            xslt.Load(myReader, settings, New XmlUrlResolver())

            Dim argsList As New XsltArgumentList
            If Not IsNothing(comboTopicFilter.ComboBox.SelectedValue) Then
                If (comboTopicFilter.ComboBox.SelectedValue.ToString.Length > 2) Then
                    argsList.AddParam("topicfilter", "", comboTopicFilter.ComboBox.SelectedValue.ToString.Trim)
                End If
            End If

            If (bnTopicName.Checked) Then
                argsList.AddParam("showtopicname", "", "1")
            End If

            Dim output As New StringWriter
            xslt.Transform(xmlDoc.CreateNavigator, argsList, output)
            WebBrowser2.DocumentText = output.ToString

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Show Table Data")
        End Try
    End Sub

    Private Sub ShowTopicSummary(iXmlsourceDoc As XmlDocument)
        Try
            Dim settings As New XsltSettings
            settings.EnableScript = True

            Dim myAssembly As [Assembly]
            myAssembly = [Assembly].GetExecutingAssembly()
            Dim myReader As XmlTextReader = New XmlTextReader(myAssembly.GetManifestResourceStream("DocsToolbox.TopicDrilldown.xslt"), XmlNodeType.Document, Nothing)


            Dim xslt As New XslCompiledTransform
            xslt.Load(myReader, settings, New XmlUrlResolver())

            Dim argsList As New XsltArgumentList
            If Not IsNothing(comboTopicFilter.ComboBox.SelectedValue) Then
                If (comboTopicFilter.ComboBox.SelectedValue.ToString.Length > 2) Then
                    argsList.AddParam("topicfilter", "", comboTopicFilter.ComboBox.SelectedValue.ToString.Trim)
                End If
            End If

            If (bnTopicName.Checked) Then
                argsList.AddParam("showtopicname", "", "1")
            End If

            Dim output As New StringWriter
            xslt.Transform(iXmlsourceDoc.CreateNavigator, argsList, output)

            Form2.Close()
            Form5.WebBrowser1.DocumentText = output.ToString
            Form5.ShowDialog()

        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Async Function GetMyData() As Task
        Try
            Dim sAuthor As String = My.Settings.Author.Trim
            If sAuthor.Length < 2 Then
                MsgBox("No author specified", MsgBoxStyle.Information, "Load My Data")
                Exit Function
            End If

            Dim sUri As String = "http://csiwebapi.cloudapp.net/SkyEyeWho/" + My.Settings.Author.Trim
            Dim myClient As New HttpClient
            Dim arrData As Byte() = Await myClient.GetByteArrayAsync(sUri)
            Dim sResponse As String = System.Text.Encoding.UTF8.GetString(arrData, 0, arrData.Length)

            Dim json As JsonSerializer = New JsonSerializer
            json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
            json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace
            json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
            json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore

            Dim xmlDoc As XmlDocument = JsonConvert.DeserializeXmlNode(sResponse, "Root")


            Dim verbatimsTextNode As XmlNode = xmlDoc.DocumentElement.SelectSingleNode("//VerbatimsText")
            Dim sVerbatims As String = verbatimsTextNode.InnerText
            sVerbatims = CutFirstLast(sVerbatims)
            verbatimsTextNode.InnerText = ""
            Dim sVerbatim As String

            For Each sVerbatim In sVerbatims.Split(",")

                Dim sItems As String() = sVerbatim.Split(New String() {"[DText]"}, StringSplitOptions.None)
                If sItems.Length = 7 Then
                    Dim newElem As XmlElement = xmlDoc.CreateElement("Verbatim")
                    Dim endNode As XmlNode = verbatimsTextNode.AppendChild(newElem)
                    Dim newWhen As XmlElement = xmlDoc.CreateElement("When")
                    newWhen.InnerText = sItems(0).Substring(1, sItems(0).IndexOf("T") - 1)
                    endNode.AppendChild(newWhen)

                    Dim newWhat As XmlElement = xmlDoc.CreateElement("What")
                    newWhat.InnerText = sItems(1)
                    endNode.AppendChild(newWhat)

                    Dim newContent As XmlElement = xmlDoc.CreateElement("Content")
                    newContent.InnerText = sItems(3).ToString
                    endNode.AppendChild(newContent)

                    Dim newUrl As XmlElement = xmlDoc.CreateElement("TopicUrl")
                    newUrl.InnerText = sItems(4).ToString
                    endNode.AppendChild(newUrl)

                    Dim newName As XmlElement = xmlDoc.CreateElement("TopicName")
                    newName.InnerText = sItems(5).ToString
                    endNode.AppendChild(newName)
                End If

            Next

            Dim sAppFolder As String = AppDomain.CurrentDomain.BaseDirectory
            xmlDoc.Save(sAppFolder + "MyData.xml")

            Dim settings As New XsltSettings
            settings.EnableScript = True

            Dim myAssembly As [Assembly]
            myAssembly = [Assembly].GetExecutingAssembly()
            Dim myReader As XmlTextReader = New XmlTextReader(myAssembly.GetManifestResourceStream("DocsToolbox.Me.xslt"), XmlNodeType.Document, Nothing)


            Dim xslt As New XslCompiledTransform
            xslt.Load(myReader, settings, New XmlUrlResolver())

            Dim output As New StringWriter
            xslt.Transform(xmlDoc.CreateNavigator, Nothing, output)
            WebBrowser1.DocumentText = output.ToString

        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            ToolStripStatusLabel1.Text = "Ready"
            Me.Cursor = Cursors.Default
            Form2.Close()
        End Try
    End Function

    Private Sub GetTopicData(sContentId As String)

        GetTopicRollup(GetTopicFilter(sContentId), 0)
        Me.Cursor = Cursors.WaitCursor
        Form2.ShowDialog()

    End Sub

    Private Sub GetVerbatims()

        If My.Settings.Author.Length < 1 Then
            MsgBox("No author configured", MsgBoxStyle.Information, "Get Verbatims")
            Exit Sub
        End If

        GetTopicRollup(GetVerbatimsFilter, 2)

        Me.Cursor = Cursors.WaitCursor
        Form2.ShowDialog()

    End Sub

    Private Sub FilterTopics()
        Try

            Dim sSource As String = My.Settings.AllTopicsData
            If sSource.Length < 2 Then
                Exit Sub
            End If

            Dim xmlDoc As New XmlDocument
            xmlDoc.LoadXml(sSource)

            ShowTable(xmlDoc)

        Catch ex As Exception
            MsgBox("Failed to filter data", MsgBoxStyle.Exclamation, "Filter Data")
        End Try
    End Sub

    Private Sub ToolStripButton2_Click(sender As Object, e As EventArgs) Handles ToolStripButton2.Click

        If My.Settings.Author.Trim.Length < 2 Then
            MsgBox("No author specified", MsgBoxStyle.Information, "Load My Data")
            Exit Sub
        End If

        ToolStripStatusLabel1.Text = "Loading data"
        Me.Cursor = Cursors.WaitCursor
        GetMyData()
        Form2.ShowDialog()
    End Sub

    Private Sub SettingsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SettingsToolStripMenuItem.Click
        Form3.ShowDialog()
        GetTitle()
        GetComboData()
    End Sub

    Private Sub CopyToClipoboard(iWebBrowser As WebBrowser)
        If Not IsNothing(iWebBrowser.Document) Then
            Me.Cursor = Cursors.AppStarting

            iWebBrowser.Document.ExecCommand("SelectAll", False, Nothing)
            iWebBrowser.Document.ExecCommand("Copy", False, Nothing)
            iWebBrowser.Document.ExecCommand("Unselect", False, Nothing)

            ToolStripStatusLabel1.Text = "Data copied to clipboard successfully"
            Me.Cursor = Cursors.Default
        End If

    End Sub

    Private Sub CopyToolStripButton1_Click(sender As Object, e As EventArgs) Handles CopyToolStripButton1.Click
        CopyToClipoboard(WebBrowser1)
    End Sub

    Private Sub CopyToolStripButton_Click(sender As Object, e As EventArgs) Handles CopyToolStripButton.Click
        CopyToClipoboard(WebBrowser2)
    End Sub

    Private Sub CopyToolStripButton2_Click(sender As Object, e As EventArgs) Handles CopyToolStripButton2.Click
        CopyToClipoboard(WebBrowser3)
    End Sub

    Private Sub CopyToolStripButton3_Click(sender As Object, e As EventArgs) Handles CopyToolStripButton3.Click
        CopyToClipoboard(WebBrowser4)
    End Sub

    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        GetAllTopicsData()
    End Sub

    Private Sub TopicsFilterToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles TopicsFilterToolStripMenuItem.Click
        ShowLoadFilter()
    End Sub

    Private Sub AllTopicsDataToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AllTopicsDataToolStripMenuItem.Click
        ShowDataFile(1)
    End Sub

    Private Sub TopicDataToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles TopicDataToolStripMenuItem.Click
        ShowDataFile(0)
    End Sub

    Private Sub MyDataToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MyDataToolStripMenuItem.Click
        ShowDataFile(2)
    End Sub

    Private Sub VerbatimDataToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VerbatimDataToolStripMenuItem.Click
        ShowDataFile(3)
    End Sub
    Private Sub comboTopicFilter_SelectedIndexChanged(sender As Object, e As EventArgs) Handles comboTopicFilter.SelectedIndexChanged
        FilterTopics()
    End Sub

    Private Sub comboDrilldown_SelectedIndexChanged(sender As Object, e As EventArgs) Handles comboDrilldown.SelectedIndexChanged
        LoadIndex()
    End Sub

    Private Sub comboVerbatims_SelectedIndexChanged(sender As Object, e As EventArgs) Handles comboVerbatims.SelectedIndexChanged
        ShowVerbatims()
    End Sub
    Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
        Form4.ShowDialog()
    End Sub

    Private Sub OpenToolStripButton_Click(sender As Object, e As EventArgs) Handles OpenToolStripButton.Click
        Me.Cursor = Cursors.WaitCursor
        LoadIndex()
    End Sub

    Private Sub WebBrowser3_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles WebBrowser3.Navigating

        Dim sUrl As String = e.Url.ToString

        If sUrl.Contains("javascript") Then
            sUrl = sUrl.Substring(sUrl.IndexOf("(") + 1)
            sUrl = sUrl.Substring(0, sUrl.Length - 2)
            e.Cancel = True
            GetTopicData(sUrl)
        End If
    End Sub

    Private Sub ToolStripButton3_Click(sender As Object, e As EventArgs) Handles ToolStripButton3.Click
        GetVerbatims()
    End Sub


End Class
